package com.wealth.member.web.controller;

import iaas.enums.StatusEnum;
import iaas.enums.YesOrNoEnum;
import iaas.redis.RedisService;
import iaas.utils.RedirectMessage;
import iaas.utils.ResultObject;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.coupon.entity.Coupon;
import com.wealth.coupon.enums.CouponModeEnum;
import com.wealth.coupon.service.ICouponRecordService;
import com.wealth.coupon.service.ICouponService;
import com.wealth.member.entity.Address;
import com.wealth.member.entity.Member;
import com.wealth.member.service.IAddressService;
import com.wealth.system.entity.Corporation;
import com.wealth.system.web.controller.BaseController;

/**
 * @author chan
 * 收货地址
 */

@Controller
@RequestMapping("/manage/address")
public class AddressController extends BaseController {
	
	Logger logger = Logger.getLogger(AddressController.class);
	
	@Autowired
	private IAddressService addressService;
	@Autowired
	private RedisService redisService;
	@Autowired
	private ICouponRecordService couponRecordService;
	@Autowired
	private ICouponService couponService;
	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Classify对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void init(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
		try {
			if (id != -1) {
				Address address = addressService.get(id);
				model.addAttribute("address", address);
			}
		} catch (Exception e) {
			logger.error("收货地址初始化错误", e);
		}
	}
	
	/**
	 * 列表
	 */
	@RequestMapping
	public String list(Model model,@RequestParam(required=false) String returnURL){
		try {
			List<Address> addressList = addressService.getAddressByMemberIdAndStatusNot(memberid, StatusEnum.DELETE.getValue());
			List<Address> addlist = addressService.findByMemberId(memberid);
			model.addAttribute("addressList", addressList);
			model.addAttribute("addlist", addlist);
			return "address/list";
		} catch (Exception e) {
			logger.error("收货地址列表错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 订单选择收货地址列表
	 */
	@RequestMapping(value="/select")
	public String select(Model model,@RequestParam(required=false) String returnURL){
		try {
			if(returnURL!=null){
				//member order requeset mapping
				redisService.set("morm_"+memberid, returnURL);
			}
			List<Address> addressList = addressService.getAddressByMemberIdAndStatusNot(memberid, StatusEnum.DELETE.getValue());
			model.addAttribute("addressList", addressList);
			return "address/select";
		} catch (Exception e) {
			logger.error("订单选择收货地址列表", e);
			return "system/500";
		}
	}
	
	/**
	 * 详情
	 */
	@ResponseBody
	@RequestMapping(value="/{id}")
	public Address addressInfo(Model model,@PathVariable("id") Long id){
		
		try {
			Address address = addressService.get(id);
			return address;
		} catch (Exception e) {
			logger.error("收货地址详情错误,id="+id, e);
			return null;
		}
	}
	
	
	/**
	 * 新增收货地址页面
	 */
	@RequestMapping(value="/create",method = RequestMethod.GET)
	public String createForm(Model model,HttpServletRequest request){
		try {
			String type=request.getParameter("type");
			if(request.getParameter("prevurl")!=null){
				model.addAttribute("prevurl", request.getParameter("prevurl"));
			}
			model.addAttribute("type", type);
			return "address/create";
		} catch (Exception e) {
			logger.error("新增收货地址页面错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 新增收货地址
	 */
	@RequestMapping(value="/create",method = RequestMethod.POST)
	public String create(Model model,Address address,HttpServletRequest request,RedirectAttributes redirectAttributes){
		try {
			String type=request.getParameter("type");
			//获得默认地址
			if(address.getIsDefault()==1){
				Address temp = addressService.getAddressDefault(memberid);
				if(temp!=null){
					temp.setIsDefault(0);
					addressService.save(temp);
				}
			}
			
			address.setCorp(new Corporation(corpid));
			address.setMember(new Member(memberid));
			address.setCreateTime(new Date());
			address.setStatus(StatusEnum.NORMAL.getValue());
			addressService.save(address);
			/*//先保存地址，再获取折扣劵
			if(type.equals("1")){
				//新增地址获取优惠券
				Coupon coupon =  couponService.findByMode(2);
				if(coupon!=null){
					if(couponRecordService.generateCoupon(memberid, corpid, CouponModeEnum.COMPLETEADDRESS.getValue()).getCode().equals("000")){
						redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("领取优惠券成功"));
					}else{
						redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("优惠券全部发光了"));
					}
				}
				
			}*/
			if(request.getParameter("prevurl")!=null){
				return "redirect:/"+request.getParameter("prevurl");
			}
			return "redirect:/manage/address";
		} catch (Exception e) {
			logger.error("新增收货地址错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 编辑收货地址页面
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.GET)
	public String updateForm(Model model,HttpServletRequest request ,@PathVariable("id") Long id){
		try {
			
			Address address = addressService.get(id);
			model.addAttribute("address", address);
			
			if(request.getParameter("prevurl")!=null){
				model.addAttribute("prevurl", request.getParameter("prevurl"));
			}
			return "address/update";

		} catch (Exception e) {
			logger.error("收货地址编辑页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 编辑收货地址
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.POST)
	public String addressUpdate(Model model,HttpServletRequest request, @ModelAttribute("address") Address address,@PathVariable("id") Long id){
		try {
			
			//获得默认地址
//			if(address.getIsDefault()==1){
//				Address temp = addressService.getAddressDefault(memberid);
//				if(temp!=null){
//					temp.setIsDefault(0);
//					addressService.save(temp);
//				}
//			}
			if(address.getIsDefault()==1){
				Address temp = addressService.getAddressDefault(memberid);
				if(temp!=null){
					if(temp.getId()!=address.getId()){
						temp.setIsDefault(0);
						addressService.save(temp);
					}
					
				}
			}
			addressService.save(address);

			if(request.getParameter("prevurl")!=null){
				return "redirect:/"+request.getParameter("prevurl");
			}
			return "redirect:/manage/address";
		} catch (Exception e) {
			logger.error("编辑收货地址错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 删除
	 */
	@RequestMapping(value="/delete/{id}",method = RequestMethod.GET)
	public String addressUpdate(Model model,@PathVariable("id") Long id){
		try {
			addressService.deleteLogical(id);
			return "redirect:/manage/address";
		} catch (Exception e) {
			logger.error("删除收货地址错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 设置该订单的收货地址
	 * 这里会将这个地址设置成用户的默认收货地址
	 * FIXME 应在缓存中设置该订单的默认地址
	 */
	@RequestMapping(value="/send/{id}",method = RequestMethod.GET)
	public String send(Model model,HttpServletRequest request,HttpSession session,@PathVariable Long id){
		try {
			
			//将默认地址设置为普通地址
			Address temp = addressService.getAddressDefault(memberid);
			if(temp!=null){
				temp.setIsDefault(0);
				addressService.save(temp);
			}
			
			//设置该新地址为默认地址
			Address address = addressService.get(id);
			address.setIsDefault(YesOrNoEnum.YES.getValue());
			addressService.save(address);
			
			
			
			String returnURL  = redisService.get("morm_"+memberid);
			return "redirect:"+returnURL;
			
		} catch (Exception e) {
			logger.error("设置订单的收货地址错误,id="+id, e);
			return "system/500";
		}
	}
	
	
	

	/**
	 * 设置默认地址
	 */
	@RequestMapping(value="/updateDefault",method = RequestMethod.POST)
	@ResponseBody
	public ResultObject isDefault(Model model,HttpServletRequest request,Long addressId){
		try {
			//将默认地址设置为普通地址
			Address temp = addressService.getAddressDefault(memberid);
			if(temp!=null){
				temp.setIsDefault(0);
				addressService.save(temp);
			}
			
			//设置该新地址为默认地址
			Address address = addressService.get(addressId);
			address.setIsDefault(YesOrNoEnum.YES.getValue());
			addressService.save(address);
			
			return new ResultObject("000", "修改成功", "");
		} catch (Exception e) {
			logger.error("新增收货地址页面错误", e);
			return new ResultObject("999", "修改失败", "");
		}
	}
	
}


